package cerebrum.common;


import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import java.util.Set;


public class ConfigPropertiesUtil {
    private ConfigPropertiesUtil() {

    }

    //创建Properties对象
    private static Properties property = new Properties();
    private static String filePath;


    static {
        try {
            String rootPath = new File("").getCanonicalPath();
            filePath = rootPath + File.separator + CommonConst.PROPERTY_CONFIG_PATH;
        } catch (IOException e) {
            e.printStackTrace();
        }
        File file = new File(filePath);
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try (
                InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8);
                BufferedReader reader = new BufferedReader(inputStreamReader);
        ) {
            property.load(reader);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取字符串类型的值
     *
     * @param key
     * @return
     */
    public static String get(String key) {
        return property.getProperty(key);
    }

    /**
     * 获取Integer类型的值
     *
     * @param key
     * @return
     */
    public static Integer getInteger(String key) {
        String value = get(key);
        return null == value ? null : Integer.valueOf(value);
    }

    public static double getDouble(String key) {
        String value = get(key);
        return EmptyChecker.isEmpty(value) ? -1 : Double.parseDouble(value);
    }

    /**
     * 获取Boolean类型的值
     *
     * @param key
     * @return
     */
    public static Boolean getBoolean(String key) {
        String value = get(key);
        return null == value ? null : Boolean.valueOf(value);
    }

    public static Set<String> getKeys() {
        return property.stringPropertyNames();
    }

    /**
     * 设置一个键值对
     *
     * @param key
     * @param value
     */
    public static void set(String key, String value) {
        property.setProperty(key, value);
        try (OutputStreamWriter oStreamWriter = new OutputStreamWriter(new FileOutputStream(new File(filePath)), StandardCharsets.UTF_8);) {
            property.store(oStreamWriter, "");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加一个键值对
     *
     * @param key
     * @param value
     */
    public static void add(String key, Object value) {
        property.put(key, value);
    }

    public static void clean() {
        Set<String> set = getKeys();
        for (String key : set) {
            set(key, "");
        }
    }

}
